<?php

namespace App\Http\Controllers\Wechat\ServiceAccount;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Product;
use App\Models\CartItem;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Session;

class CartController extends Controller
{
    /**
     * 显示购物车页面
     */
    public function index()
    {
        // 获取当前用户的购物车商品
        $cartItems = $this->getCartItems();
        
        // 计算总价
        $totalPrice = $cartItems->sum(function ($item) {
            return $item->product->price * $item->quantity;
        });
        
        return view('wechat.service_account.cart', compact('cartItems', 'totalPrice'));
    }
    
    /**
     * 添加商品到购物车
     */
    public function add(Request $request)
    {
        $request->validate([
            'product_id' => 'required|exists:products,id',
            'quantity' => 'required|integer|min:1',
        ]);
        
        $productId = $request->product_id;
        $quantity = $request->quantity;
        
        // 获取商品信息
        $product = Product::findOrFail($productId);
        
        // 检查库存
        if ($product->stock < $quantity) {
            return response()->json([
                'success' => false,
                'message' => '商品库存不足'
            ]);
        }
        
        // 如果用户已登录，则保存到数据库
        if (Auth::guard('wechat')->check()) {
            $userId = Auth::guard('wechat')->id();
            
            // 检查购物车中是否已有该商品
            $cartItem = CartItem::where('user_id', $userId)
                ->where('product_id', $productId)
                ->first();
                
            if ($cartItem) {
                // 如果已有该商品，则更新数量
                $cartItem->quantity += $quantity;
                $cartItem->save();
            } else {
                // 如果没有该商品，则创建新记录
                CartItem::create([
                    'user_id' => $userId,
                    'product_id' => $productId,
                    'quantity' => $quantity
                ]);
            }
        } else {
            // 如果用户未登录，则保存到 Session
            $cart = Session::get('cart', []);
            
            if (isset($cart[$productId])) {
                // 如果已有该商品，则更新数量
                $cart[$productId] += $quantity;
            } else {
                // 如果没有该商品，则添加
                $cart[$productId] = $quantity;
            }
            
            Session::put('cart', $cart);
        }
        
        return response()->json([
            'success' => true,
            'message' => '商品已添加到购物车'
        ]);
    }
    
    /**
     * 更新购物车中商品的数量
     */
    public function update(Request $request)
    {
        $request->validate([
            'product_id' => 'required|exists:products,id',
            'quantity' => 'required|integer|min:1',
        ]);
        
        $productId = $request->product_id;
        $quantity = $request->quantity;
        
        // 获取商品信息
        $product = Product::findOrFail($productId);
        
        // 检查库存
        if ($product->stock < $quantity) {
            return response()->json([
                'success' => false,
                'message' => '商品库存不足'
            ]);
        }
        
        // 如果用户已登录，则更新数据库
        if (Auth::guard('wechat')->check()) {
            $userId = Auth::guard('wechat')->id();
            
            $cartItem = CartItem::where('user_id', $userId)
                ->where('product_id', $productId)
                ->first();
                
            if ($cartItem) {
                $cartItem->quantity = $quantity;
                $cartItem->save();
            }
        } else {
            // 如果用户未登录，则更新 Session
            $cart = Session::get('cart', []);
            
            if (isset($cart[$productId])) {
                $cart[$productId] = $quantity;
                Session::put('cart', $cart);
            }
        }
        
        return response()->json([
            'success' => true,
            'message' => '购物车已更新'
        ]);
    }
    
    /**
     * 从购物车中移除商品
     */
    public function remove(Request $request)
    {
        $request->validate([
            'product_id' => 'required|exists:products,id',
        ]);
        
        $productId = $request->product_id;
        
        // 如果用户已登录，则从数据库中删除
        if (Auth::guard('wechat')->check()) {
            $userId = Auth::guard('wechat')->id();
            
            CartItem::where('user_id', $userId)
                ->where('product_id', $productId)
                ->delete();
        } else {
            // 如果用户未登录，则从 Session 中删除
            $cart = Session::get('cart', []);
            
            if (isset($cart[$productId])) {
                unset($cart[$productId]);
                Session::put('cart', $cart);
            }
        }
        
        return response()->json([
            'success' => true,
            'message' => '商品已从购物车中移除'
        ]);
    }
    
    /**
     * 清空购物车
     */
    public function clear()
    {
        // 如果用户已登录，则清空数据库中的购物车
        if (Auth::guard('wechat')->check()) {
            $userId = Auth::guard('wechat')->id();
            CartItem::where('user_id', $userId)->delete();
        } else {
            // 如果用户未登录，则清空 Session 中的购物车
            Session::forget('cart');
        }
        
        return response()->json([
            'success' => true,
            'message' => '购物车已清空'
        ]);
    }
    
    /**
     * 获取当前用户的购物车商品
     */
    private function getCartItems()
    {
        // 如果用户已登录，则从数据库获取
        if (Auth::guard('wechat')->check()) {
            $userId = Auth::guard('wechat')->id();
            return CartItem::with('product')->where('user_id', $userId)->get();
        } else {
            // 如果用户未登录，则从 Session 获取
            $cart = Session::get('cart', []);
            $cartItems = collect();
            
            foreach ($cart as $productId => $quantity) {
                $product = Product::find($productId);
                if ($product) {
                    $cartItem = new CartItem();
                    $cartItem->product_id = $productId;
                    $cartItem->quantity = $quantity;
                    $cartItem->product = $product;
                    $cartItems->push($cartItem);
                }
            }
            
            return $cartItems;
        }
    }
}